package meth

import (
	"encoding/json"
	"fmt"
	"net/http"
	"sync"
	"test/model"
	"time"
)

var (
	devices   []model.Device
	devicesMu sync.RWMutex
	scanning  bool
)

type ScanResponse struct {
	Status  string         `json:"status"`
	Total   int            `json:"total"`
	Devices []model.Device `json:"devices"`
}

func ScanningDevice(w http.ResponseWriter, r *http.Request) {
	// 防止扫描被重复执行（互斥锁机制）
	if scanning {
		return
	}
	scanning = true
	defer func() { scanning = false }()

	// 记录开始时间
	startTime := time.Now()

	// 并发 Ping 整个子网
	ips := generateIPs(192, 168, 3)
	for _, ip := range ips {
		PingIP(ip, 1000)
	}

	fmt.Printf("[%s] 开始扫描网络...\n", startTime.Format("2006-01-02 15:04:05"))

	// 获取 ARP 表
	ArpTable := GetARPTable()
	arpMap, _ := ParseARP(ArpTable)
	filteredMap, err := filterBySubnet(arpMap, "192.168.3.0/24")
	if err != nil {
		fmt.Println(err)
	}

	results := make(chan model.Device, 512)
	var wg sync.WaitGroup

	// 最大并发数量
	maxConcurrent := 64
	guard := make(chan struct{}, maxConcurrent)

	for _, entry := range filteredMap {
		wg.Add(1)
		guard <- struct{}{}
		go func(entry ARPEntry) {
			defer wg.Done()
			defer func() { <-guard }()
			// 获取版本和设备信息
			hostname, DeviceInfo := FetchVersion(entry.IP)
			if hostname == "" {
				return
			}
			results <- model.Device{
				Hostname: hostname,
				SN:       DeviceInfo.DeviceID,
				IP:       entry.IP,
				MAC:      entry.MAC,
				Version:  DeviceInfo.FirmwareVersion,
			}
		}(entry)
	}

	go func() {
		wg.Wait()
		close(results)
	}()

	var newDevices []model.Device
	for dev := range results {
		newDevices = append(newDevices, dev)
	}

	devicesMu.Lock()
	devices = newDevices
	devicesMu.Unlock()

	// 收集结果

	fmt.Printf("[%s] 扫描完成，发现 %d 台设备，耗时 %v\n",
		time.Now().Format("2006-01-02 15:04:05"),
		len(devices),
		time.Since(startTime))

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(ScanResponse{
		Status:  "completed",
		Total:   len(newDevices),
		Devices: newDevices,
	})
}
